package com.fswan.permission;

import lombok.Data;
import org.beetl.core.Configuration;
import org.beetl.core.GroupTemplate;
import org.beetl.core.Template;
import org.beetl.core.resource.StringTemplateResourceLoader;
import java.io.IOException;
import java.io.StringWriter;
import java.util.Map;
@Data
public class BeetlScriptRule extends Rule{
    private String expression;
    @Override
    public boolean test(Account account, Role role, Map<?, ?> extraData) {
        try {
            StringTemplateResourceLoader resourceLoader = new StringTemplateResourceLoader();
            Configuration cfg = Configuration.defaultConfiguration();
            GroupTemplate gt = new GroupTemplate(resourceLoader, cfg);
            Template template = gt.getTemplate(expression);
            template.binding("role",role);
            template.binding("account",account);
            template.binding(extraData);
            StringWriter writer = new StringWriter();
            template.renderTo(writer);
            return writer.toString().trim().equalsIgnoreCase("true");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
